import axios from "axios";
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";

interface RequestInterface<T> {
  code: number;
  msg: string;
  data: T;
}

type Response<T> = Promise<T>;

const axiosInstance: AxiosInstance = axios.create({
  baseURL: "/dev",
  // timeout: 10000,
});

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log(config);
    if (!config.headers["Content-Type"]) {
      config.headers["Content-Type"] = "application/json";
    }
    return config;
  },
  (error) => {
    console.log("error", error);
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response: AxiosResponse<RequestInterface<any>, any>) => {
    if (response.status !== 200) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      window.$message({
        type: "error",
        message: "网络错误，请检查网络后再试！",
      });
      return Promise.reject("网络错误，请检查网络后再试！");
    }
    if (response.data.code === 200) {
      return response.data.data;
    } else {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      window.$message({
        type: "error",
        message: response.data.msg,
      });
      return Promise.reject(response.data.msg);
    }
  },
  (error) => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    window.$message({
      type: "error",
      message: "网络错误，请检查网络后再试！",
    });
    return Promise.reject(error);
  }
);

export const get = <T = any>(
  url: string,
  params = {},
  headers = {}
): Response<T> => {
  return axiosInstance({
    url,
    method: "get",
    params,
    headers,
  });
};

export const post = <T = any>(
  url: string,
  params = {},
  headers = {}
): Response<T> => {
  return axiosInstance({
    url,
    method: "post",
    data: params,
    headers,
  });
};

export const put = <T = any>(
  url: string,
  params = {},
  headers = {}
): Response<T> => {
  return axiosInstance({
    url,
    method: "put",
    data: params,
    headers,
  });
};
